package app;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;

import color.Rgb;

import cluster.Observation;

public class PixelBin implements Comparable{
	int r, g, b;
	int rm, gm, bm;
	int tolerance;
	public int freq = 0;
	public float relFreq = 0;
	public int cumFreq = 0;
	public float cumRelFreq = 0;
	
	ArrayList<Observation<Rgb>> colors;
	
	public PixelBin(int r, int g, int b, int tol){
		this.r = r;
		this.g = g;
		this.b = b;
		rm = r + tol;
		gm = g + tol;
		bm = b + tol;
		tolerance = tol;
		colors = new ArrayList<Observation<Rgb>>();
		
	}
	
	public boolean insideBin(Observation<Rgb> rgb){
		if(!(rgb.obs.r >= r && rgb.obs.r < rm)) return false;
		if(!(rgb.obs.g >= g && rgb.obs.g < gm)) return false;
		if(!(rgb.obs.b >= b && rgb.obs.b < bm)) return false;
		return true;
	}
	
	public boolean containsColor(Observation<Rgb> rgb){
		Iterator<Observation<Rgb>> i = colors.iterator();
		while(i.hasNext()) if(rgb.equals(i.next())) return true;
		return false;
	}
	
	public void addColor(Observation<Rgb> rgb){
		colors.add(rgb);
		freq += rgb.freq;
	}
	
	public float getAvgFreq(){
		return (float) freq / (float) colors.size();
	}
	
	public ArrayList<Rgb> getRgbArray(){
		Iterator<Observation<Rgb>> i = colors.iterator();
		ArrayList<Rgb> le = new ArrayList<Rgb>(colors.size());
		while(i.hasNext()) 
			le.add(i.next().obs);
		return le;
	}
	
	public Rgb getColor(){
		Iterator<Observation<Rgb>> i = colors.iterator();
		int f = 0;
		Rgb color = null;
		while(i.hasNext()){
			Observation<Rgb> next = i.next();
			if(next.freq > f){
				f = next.freq;
				color = next.obs;
			}
		}
		return color;
	}
	
	public ArrayList<Rgb> getColors(float ratio){
		int numColors = Math.max(1, Math.round(colors.size() * ratio));
		ArrayList<Observation<Rgb>> clone = new ArrayList<Observation<Rgb>>(colors);
		while(clone.size() > numColors){
			Iterator<Observation<Rgb>> i = clone.iterator();
			Observation<Rgb> lowest = null;
			int loFreq = Integer.MAX_VALUE;
			while(i.hasNext()){
				Observation<Rgb> next = i.next();
				if(next.freq < loFreq){
					loFreq = next.freq;
					lowest = next;
				}
			}
			clone.remove(lowest);
		}
		Iterator<Observation<Rgb>> i = clone.iterator();
		ArrayList<Rgb> rgb = new ArrayList<Rgb>(colors.size());
		while(i.hasNext()) 
			rgb.add(i.next().obs);
		return rgb;
	}

	

	public int compareTo(Object o) {
		PixelBin b = (PixelBin)o;
		if(b.getAvgFreq() < getAvgFreq()) return -1;
		if(b.getAvgFreq() > getAvgFreq()) return 1;
		return 0;
	}
	
	

}
